var startTime = "";
var endTime = "",pageSize=10,total=0,type=0;
var https="http://yrz.jiuhuakang.com";
var table,laypage,layer,element,form,liveTrime,proTrime,VideoTrime;
var listId=[];
layui.config({
    version: '1510164124181'
}).use(['laypage', 'layer', 'table','form','element'], function () {
    table = layui.table
    , laypage = layui.laypage
    , layer = layui.layer
    , element = layui.element
    , form = layui.form;
    var active = {
        getAddData: function () { //添加
            AddInfo("");
        }
        , getCheckData: function () { //批量删除
            var checkStatus = table.checkStatus('tableInfoId')
                , data = checkStatus.data;
            var dataId = "";
            for (var i = 0; i < data.length; i++) {
                dataId += data[i].id + ",";
            }
            if (dataId.length > 0) {
                dataId = dataId.substring(0, dataId.length - 1);
                DeleteAjaxHttp(dataId, deleteUrl);
            } else {
                top.layer.msg("请选择你要删除的数据!!");
            }
        }
    };
    form.on('select(selectState)', function(obj){
        var id = $(obj.elem).attr("data-id");
        var val = obj.value;
        updateFindStateInfoById(id,val);
    });

    $('.demoTable .layui-btn').on('click', function () {
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });
    //监听操作
    form.on('switch(stateSelectDemo)', function (obj) {
        pageNo = 1;
        inituserdata();
    });

    //监听操作
    form.on('switch(typeSelectDemo)', function (obj) {
        pageNo = 1;
        inituserdata();
    });
    //监听搜索操作
    form.on('submit(formSubSearch)', function (obj) {
        pageNo = 1;
        inituserdata();
    });

    //监听工具条
    table.on('tool(tableInfo)', function (obj) {
        var data = obj.data;
        if (obj.event === 'editProduct') {
            roomId=data.roomid;
            editProduct();
        } else if (obj.event === 'playVideo') {
            roomId=data.roomid;
            playVideo();
        }
    });

    //监听单元格编辑
    table.on('edit(tableInfo)', function (obj) {
        let value = obj.value //得到修改后的值
            , data = obj.data //得到所在行所有键值
            , field = obj.field; //得到字段
        layer.confirm("您确定将此条信息修改为:" + value + "?", {icon: 3, title: '提示信息'}, function (index) {
            index = top.layer.msg('提交中，请稍候', {icon: 16, time: false, shade: 0.8});
            editInfo(data.id, field, value);
        });
    });
    liveTrime=window.setInterval(inituserdata,1000);
});

function inituserdata() {
    index = top.layer.msg('加载中，请稍候', {icon: 16, time: false, shade: 0.8});
    $.ajax({
        url: https + "/live/getLiveCount",
        cache: false,
        headers: {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "*",
            "Access-Control-Allow-Headers": "Authorization",
            "Authorization": GetTokenInfo()
        },
        contentType : 'application/json',
        success: function (data) {
            totalRecords=0;
            var dataInfo =[];
            if(data.rtnCode==200){
                dataInfo = data.data.room_info;
                totalRecords = data.data.total;
            }
            if(isNotNull(dataInfo)){
                window.clearInterval(liveTrime);
            }
            layer.close(index);
            table.render({
                elem: '#tableInfo'
                , data: dataInfo
                , id: "tableInfoId"
                , cols: [[
                    {type: 'checkbox'}
                    , {field: 'roomid', align: "center", width: 150, title: '直播间ID', sort: true}
                    , {field: 'name', align: "center", edit: 'text', title: '直播间名称'}
                    , {field: 'anchor_name', align: "center", edit: 'text', title: '主播名'}
                    , {field: 'cover_img', align: "center", width: 150, title: '直播间背景图', templet: function (res) {
                            return "<img src='"+ res.cover_img +"'/>";
                        }
                    }
                    , {
                        field: 'share_img', align: "center", width: 150, title: '直播间分享图链接', templet: function (d) {
                            return "<img src="  + d.share_img + ">";
                        }
                    }
                        , {field: 'start_time', align: "center", title: '直播间开始时间', templet: function (d) {
                            return timestampToTime(d.start_time*1000);
                        }}, {field: 'end_time', align: "center", title: '直播计划结束时间', templet: function (d) {
                            return timestampToTime(d.end_time*1000);
                        }}
                    , {field: 'live_status', align: "center", edit: 'text', width: 150, title: '直播间状态', sort: true, templet: function (d) {
                            let info="";
                            if(d.live_status==101){
                                info='直播中';
                            }if(d.live_status==102){
                                info='未开始';
                            }if(d.live_status==103){
                                info='已结束';
                            }if(d.live_status==104){
                                info='禁播';
                            }if(d.live_status==105){
                                info='暂停';
                            }if(d.live_status==106){
                                info='异常';
                            }if(d.live_status==107){
                                info='已过期';
                            }
                            return info;
                        }}
                    , {field: 'del', align: "center", width: 150, title: '操作', templet: '#barDemo', unresize: true}
                ]]
            });
        }
    });
}
function playVideo() {
    layer.open({
        type: 1,
        title: ['视频列表', 'color:red;font;font-weight: 600;'],
        area: ['950px', '800px'],
        shadeClose: false, //点击遮罩关闭
        content: '<div class="form-group-col-2 add">\n' +
            '                    <div class="layui-fluid" style="margin-top: 15px;">\n' +
            '                        <table id="tableInfo2" lay-filter="tableInfo2"></table>\n' +
            '                        <div id="page" class="text-center"></div>\n' +
            '                    </div>\n' +
            '                </div>'
    });
    VideoTrime=window.setInterval(initPlayVideo,1000);
}
function initPlayVideo() {
    $.ajax({
        url: https + "/live/getLiveinfo",
        cache: false,
        headers: {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "*",
            "Access-Control-Allow-Headers": "Authorization",
            "Authorization": GetTokenInfo()
        },
        contentType : 'application/json',
        data:{
            "roomId":roomId,
            "page":pageNo,
            "pageSize":pageSize
        },
        success: function (data) {
            totalRecords = 0;
            var dataInfo = [];
            if (data.rtnCode == 200) {
                dataInfo = data.data.live_replay;
                totalRecords = data.data.total;
            }
            if(isNotNull(dataInfo)){
                window.clearInterval(VideoTrime);
            }
            table.render({
                elem: '#tableInfo2'
                , data: dataInfo
                , id: "tableInfoId2"
                , cols: [[
                    {field: 'create_time', align: "center", title: '回放视频创建时间', sort: true,templet:function (d) {
                        return d.create_time;
                    }}
                    , {field: 'expire_time', align: "center", title: '回放视频过期时间'}
                    , {field: 'media_url', align: "center",  title: '回放视频',templet:function (d) {
                        var loadstr = '<video width="100%" height="100%"  controls="controls" autobuffer="autobuffer"  autoplay="autoplay" loop="loop"><source src="'+d.media_url+'" type="video/mp4"></source></video>'
                        return loadstr;
                    }}
                ]]
            });
            vpage();
        }
    })
}
function editProduct() {
    layer.open({
        type: 1,
        title: ['添加直播商品', 'color:red;font;font-weight: 600;'],
        area: ['950px', '800px'],
        shadeClose: false, //点击遮罩关闭
        content: '<div class="form-group-col-2 add">\n' +
            '                    <div class="layui-fluid" style="margin-top: 15px;">\n' +
            '                        <table id="tableInfos" lay-filter="tableInfos"></table>\n' +
            '                        <div id="page" class="text-center"></div>\n' +
            '                    </div>\n' +
            '                    <div class="form-group-col-2">\n' +
            '                        <div class="form-cont">\n' +
            '                            <input type="button" value="我已经选好了" class="btn btn-danger" onclick="submitInfo()"/>\n' +
            '                        </div>\n' +
            '                    </div>\n' +
            '                </div>'
    });
    proTrime=window.setInterval(initEditProduct,1000);
}
function submitInfo() {
    let listIds=listId.join(',');
    $.ajax({
        url: https + "/live/getAddgoodsLive",
        cache: false,
        headers: {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "*",
            "Access-Control-Allow-Headers": "Authorization",
            "Authorization": GetTokenInfo()
        },
        contentType : 'application/json',
        data:{
            "integers":listIds,
            "roomId":roomId
        },
        success: function (data) {
            if(data.rtnCode==500){
                layer.alert(errorMsg(data.data));
            }else{
                layer.alert("提交成功!");
            }
        }
    })
}
function errorMsg(code) {
    if(code==-1){
        return "系统错误";
    }
    if(code==1){
        return "未创建直播间";
    }if(code==1003){
        return "商品id不存在";
    }if(code==47001){
        return "入参格式不符合规范";
    }if(code==200002){
        return "入参错误";
    }if(code==300001){
        return "禁止创建/更新商品 或 禁止编辑&更新房间";
    }if(code==300002){
        return "名称长度不符合规则";
    }if(code==300006){
        return "图片上传失败（如：mediaID过期）";
    }if(code==300022){
        return "此房间号不存在";
    }if(code==300023){
        return "房间状态 拦截（当前房间状态不允许此操作）";
    }if(code==300024){
        return "商品不存在";
    }if(code==300025){
        return "商品审核未通过";
    }if(code==300026){
        return "房间商品数量已经满额";
    }if(code==300027){
        return "导入商品失败";
    }if(code==300028){
        return "房间名称违规";
    }if(code==300029){
        return "主播昵称违规";
    }if(code==300030){
        return "主播微信号不合法";
    }if(code==300031){
        return "直播间封面图不合规";
    }if(code==300032){
        return "直播间分享图违规";
    }if(code==300034){
        return "主播微信昵称长度不符合要求";
    }if(code==300035){
        return "主播微信号不存在";
    }if(code==300036){
        return "主播微信号未实名认证";
    }if(code==300037){
        return "购物直播频道封面图不合规";
    }if(code==9410000){
        return "直播间列表为空";
    }if(code==9410001){
        return "获取房间失败";
    }if(code==9410002){
        return "获取商品失败";
    }if(code==9410003){
        return "获取回放失败";
    }
}
function initEditProduct() {
    $.ajax({
        url: https + "/live/getCommodityLive",
        cache: false,
        headers: {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "*",
            "Access-Control-Allow-Headers": "Authorization",
            "Authorization": GetTokenInfo()
        },
        contentType : 'application/json',
        data:{
            "page":pageNo,
            "pageSize":pageSize
        },
        success: function (data) {
            totalRecords = 0;
            var dataInfo = [];
            if (data.rtnCode == 200) {
                dataInfo = data.data.goods;
                totalRecords = data.data.total;
            }
            if(isNotNull(dataInfo)){
                window.clearInterval(proTrime);
            }
            table.render({
                elem: '#tableInfos'
                , data: dataInfo
                , id: "tableInfoIds"
                , cols: [[
                    {field: 'goodsId', align: "center", width: 80, title: '商品ID', sort: true}
                    , {field: 'name', align: "center", edit: 'text', title: '商品名称'}
                    , {
                        field: 'coverImgUrl', align: "center", width: 150, title: '商品图片链接', templet: function (d) {
                            return '<img src="'+d.coverImgUrl+'"/>';
                        }
                    }, {
                        field: 'thirdPartyTag', align: "center", width: 150, title: '添加商品方式', templet: function (d) {
                            return d.thirdPartyTag==1?"API 添加的商品":"直播控制台添加";
                        }
                    }
                    , {
                        field: 'priceType', align: "center", title: '价格', templet: function (d) {
                            let info="";
                            if(d.priceType==1){
                                info="一口价:"+d.price;
                            }if(d.priceType==2){
                                info="价格区间:"+d.price+" - "+d.price2;
                            }if(d.priceType==3){
                                info="折扣价:"+"原价："+d.price+",现价 "+d.price2;
                            }
                            return info;
                        }
                    }
                    // , {field: 'url', align: "center", edit: 'text', width: 80, title: '商品小程序路径', sort: true}
                    , {field: 'del', align: "center", width: 120, title: '操作',templet: function (res) {
                            let info = "";
                            if ($.inArray(res.goodsId, listId) > -1) {
                                info = '<span class="btn btn-danger" data-id="' + res.goodsId + '" onclick="chooseThis(this)">已选取</span>';
                            } else {
                                info = '<span class="btn btn-info" data-id="' + res.goodsId + '" onclick="chooseThis(this)">选取</span>';
                            }
                            return info;
                    }}
                ]]
            });
            page();
        }
    })
}
//分页
function page() {
    laypage.render({
        elem: 'page' //注意，这里的 test1 是 ID，不用加 # 号
        , count: totalRecords //数据总数，从服务端得到
        , curr: pageNo //获取起始页 location.hash.replace('#!fenye=', '')
        , hash: 'fenye' //自定义hash值
        , layout: ['count', 'prev', 'page', 'next', 'skip']
        , jump: function (obj, first) {
            //首次不执行
            if (!first) {
                pageNo = obj.curr;// 当前页数;
                pageRecords = obj.limit;// 当前页面记录数
                initEditProduct();
            }
        }
    });
}
//分页
function vpage() {
    laypage.render({
        elem: 'page' //注意，这里的 test1 是 ID，不用加 # 号
        , count: totalRecords //数据总数，从服务端得到
        , curr: pageNo //获取起始页 location.hash.replace('#!fenye=', '')
        , hash: 'fenye' //自定义hash值
        , layout: ['count', 'prev', 'page', 'next', 'skip']
        , jump: function (obj, first) {
            //首次不执行
            if (!first) {
                pageNo = obj.curr;// 当前页数;
                pageRecords = obj.limit;// 当前页面记录数
                initPlayVideo();
            }
        }
    });
}